<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\customer\admin;
use app\customer\model\Customer as CustomerModel;
use service\Format;
use app\admin\admin\Base;


/**
 * 门店客服管理
 * @package app\user\controller
 */
class Customer extends Base
{
    /**
     * 客服列表
     * @author 晓风<215628355@qq.com>
     * @return mixed
     */
    public function index($store_id = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map = [];
        if($store_id){
            $map[] = ['customer_shop.store_id',"=",$store_id];
        }
        $param = $this->request->param();    
        if ($param["self_store_id"]) {
            $map[] = ['customer_shop.store_id',"=",$param["self_store_id"]];
        }    
        if ($param["store_name"]) {
            $map[] = ["customer_shop.store_name","like",'%' . $param["store_name"] . '%'];
        }  
        if ($param["mobile"]) {
            $map[] = ["user.mobile","like",'%' . $param["mobile"] . '%'];
        }  
        // 排序
        $order = $this->getOrder('customer.id desc');

        $data_list = CustomerModel::getList($map,$order);
   
        $fields = [
            //['id', 'ID'],
            ['store_id', '店铺ID'],
            ['store_name', '店铺名称'],
            ['store_logo', '店铺LOGO',"picture"],
            ['mobile', '手机号', 'text'],
            ['user_nickname', '昵称'],        
            ['head_img', '头像', 'picture'],
            ['create_time', '创建时间', '','','','text-center'],
            ['status', '状态', 'status', '', ["休息","在线","忙碌"], 'text-center'],
            ['right_button', '操作', 'btn', '', '', 'text-center']
        ];
        if(!$store_id){
            $search_fields = [
                ['self_store_id', '店铺ID', 'text'],
                ['store_name', '店铺名称', 'text'],
                ['mobile', '手机号', 'text'],
            ];
        }else{
            $search_fields = [];
        }
        $layer = 1; 
        $reload = 1;
        return Format::ins()//实例化
         
            ->setTopSearch($search_fields)
            ->setPageTips( "保障稳定运行，每个店铺最多可添加100个客服")

            ->addColumns($fields)//设置字段     
            ->setTopButton(['title'=>'新增客服','href'=>['add',['store_id'=>$store_id,'layer'=>$layer],'reload'=>$reload],'icon'=>'fa fa-plus pr5','class'=>'btn btn-sm mr5 btn-primary btn-flat layeradd'])
            ->setTopButton([
                    'title'=>'设置休息',
                    'href'=>['edit',["status"=>0]],
                    'icon'=>'fa fa-ban pr5',
                    'class'=>'btn btn-sm mr5 btn-default btn-flat ajax-post confirm',
                    "extra"=>'target-form="ids"'                
                ])  
            ->setTopButton([
                    'title'=>'设置上线',
                    'href'=>['edit',["status"=>1]],
                    'icon'=>'fa fa-check-circle pr5',
                    'class'=>'btn btn-sm mr5 btn-default btn-flat ajax-post confirm',
                    "extra"=>'target-form="ids"'                
                ]) 
            ->setTopButton([
                    'title'=>'设置忙碌',
                    'href'=>['edit',["status"=>2]],
                    'icon'=>'fa fa-history pr5',
                    'class'=>'btn btn-sm mr5 btn-default btn-flat ajax-post confirm',
                    "extra"=>'target-form="ids"'                
                ]) 
            ->setRightButtons($this->right_button_layer,["edit","disable","enable"])           
            ->setData($data_list)//设置数据   
            ->replaceRightButton(["member_id"=>$this->user_id], "", "delete")
            ->fetch();//显示
    }

    /**
     * 新增
     * @author 晓风<215628355@qq.com>
     * @return mixed
     */
    public function add($store_id = 0)
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();      
            if(!$data["store_id"] || !$data["user_id"]){
                $this->error("请填写门店ID和用户");
            }                    
            $user = \app\user\model\User::where("id",$data["user_id"])->where("status",1)->find();
            if(!$user){
                $this->error("用户不正确或已禁用");
            }      
            try{            
                CustomerModel::bindUser($data["store_id"],$user["id"]);
                
                \think\Db::commit();            
            }catch(\Exception $e){
                \think\Db::rollback();          
                $this->error($e->getMessage());
            }   
            $this->success('绑定成功', cookie('__forward__'));          
        }    
        if($store_id > 0){
            $shop = \app\customer\model\Shop::where("store_id",$store_id)->find();
            if(!$shop){           
                $this->error("参数错误");
            }
            $fields = [           
                ['type' => 'static', 'name' => 'store_id2','title'=>'店铺名称',"value"=>$shop["store_name"]],
                ['type' => 'hidden', 'name' => 'store_id',"value"=>$store_id],
                ['type' => 'selectajax', 'name' => 'user_id', 'title' => '用户ID/手机/昵称',"tips"=>"用户ID/手机/昵称"],
                //['type' => 'password', 'name' => 'password', 'title' => '登录密码',"tips"=>"用户登录APP的密码"],
            ];
        }else{
            $fields = [           
                ['type' => 'number', 'name' => 'store_id', 'title' => '店铺ID',"url"=>url('searchShop')],
                ['type' => 'selectajax', 'name' => 'user_id', 'title' => '用户ID/手机/昵称',"tips"=>"用户ID/手机/昵称"],
                //['type' => 'password', 'name' => 'password', 'title' => '登录密码',"tips"=>"用户登录APP的密码"],
            ];
        }
       
        $this->assign('page_title', '新增客服');
        $this->assign('form_items', $fields);
        return $this->fetch('admin@public/add');
    }
     /**
     * 删除
     * @author 晓风<215628355@qq.com>
     * @return mixed
     */
    public function delete($ids = null){
        if(!$ids){
            $this->error("缺少参数");
        }
        CustomerModel::where("id",$ids)->delete();
        $this->success("删除成功");
    }
     /**
     * 编辑
     * @author 晓风<215628355@qq.com>
     * @return mixed
     */
    public function edit(int $status){
        $ids = input("post.ids/a");
        if(!$ids){
            $this->error("缺少参数");
        }
        CustomerModel::where("id","in",$ids)->setField("status",$status);
        $this->success("设置成功");
    }
    
      public function searchShop(){
         // 查询
        $key = input('key/s', '');
        if ($key == '') {
            return '';
        }
        $page = input('page/d', 1);
        // 数据列表
        $data_list = \app\customer\model\Shop::where('store_id', 'like', '%' . $key . '%')
            ->whereOr('store_name', 'like', '%' . $key . '%')    
            ->field('store_id,store_name,store_logo')
            ->paginate(20);
        $results = [];
        foreach ($data_list as $v) {
            $img = "";
            if(  $v['store_logo'] ){
                $v['store_logo'] = get_thumb($v['store_logo']);
                $img = '<img src="'.$v['store_logo'].'" height="18px"/>&nbsp;&nbsp;';
            }          
            $str = $img . $v['store_id'] . '/' . $v['store_name'];
            $results[] = ['id' => $v['store_id'], 'text' => $str];
        }
        $data['results'] = $results;
        $data['pagination'] = $data_list->currentPage() == $data_list->lastPage() ? ['more' => true] : ['more' => false];
        return json($data, JSON_UNESCAPED_UNICODE);
    }
}